package com.yootk.test;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * SAX解析模型
 */
public class SAXTest2 {

    public static void main(String[] args) throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "muyan.xml");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        MemberSAXHelp2 memberSAXHelp = new MemberSAXHelp2();
        parser.parse(file, memberSAXHelp);
        memberSAXHelp.getAllMembers().forEach(System.out::println);
    }
}

class Member {
    private String id;
    private String name;
    private Integer age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "【Member】用户ID = " + this.id + "、用户姓名 = " + this.name + "、用户年龄 = " + this.age;
    }
}

class MemberSAXHelp2 extends DefaultHandler {
    private List<Member> allMembers; // 保存全部的Member集合
    private String qName; // 保存元素的名称
    private Member member = null; // 获取Member对象实例

    @Override
    public void startDocument() throws SAXException {
        this.allMembers = new ArrayList<>(); // 对象实例化
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        this.qName = qName; // 在元素开始的时候获取元素名称
        if ("member".equals(qName)) {   // member元素开始
            this.member = new Member(); // 实例化Member对象
            this.member.setId(attributes.getValue("id")); // 保存id属性
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String val = new String(ch, start, length).trim(); // 文本内容
        if (!("".equals(val) || val == null)) { // 内容不为空
            if ("name".equals(this.qName)) {    // name元素文本
                this.member.setName(val);
            } else if ("age".equals(this.qName)) {  // age元素文本
                this.member.setAge(Integer.parseInt(val));
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("member".equals(qName)) {
            this.allMembers.add(this.member); // 向集合中保存对象
            this.member = null; // 断开已有的引用
        }
    }

    public List<Member> getAllMembers() {
        return allMembers;
    }
}
